Ext.define('CA.dictionary.Tree',{
    extend: 'Ext.tree.Panel',
    xtype: 'CA.dictionary.Tree',

    useArrows: true,
    rootVisible: false,
    root: { expanded: true },

    initComponent: function(){
        var config = {
            store: this.buildStore(),
            viewConfig: {
                loadMask: false
            },
            columns: [
                {
                    xtype: 'treecolumn',
                    text: 'Наименование',
                    dataIndex: 'name',
                    flex: 2
                },
                {
                    text: 'Код',
                    dataIndex: 'code',
                    renderer: function(val){ return '<span style="color:gray">' + val + '</span>'; },
                    flex: 1
                }
            ]
        };

        Ext.apply(this, config);

        this.callParent();
    },

    buildStore: function(){
        var store = Ext.create('Ext.data.TreeStore', {
            autoLoad: false,
            nodeParam: 'node',
            fields: ['code','name','id','type','view_type'],
            proxy: {
                paramOrder: ['node'],
                type: 'direct',
                directFn: Dictionary.read,
                reader: {
                    type:'json',
                    root: 'data'
                }
            },
            folderSort: true,
            sorters: [{
                property: 'name',
                direction: 'ASC'
            }]
        });

        var types = ['root','system','user'];

        store.on('append', function(node, child){
            if(node && Ext.Array.contains(types, node.internalId)){
                child.data.leaf = true;
                child.data.iconCls = 'c-icon-book';
            }
        });

        return store;
    },

    createDictionary: function(data){
        var group = this.store.getNodeById(data.type),
            sm = this.getSelectionModel();

        group.expand(false, function(){
            var node = group.findChild('id', data.id) || group.appendChild(data);

            sm.select(node);
        });
    }
});
